package org.opens.lambda;

import org.junit.Test;

import java.io.Serializable;
import java.util.Comparator;

public class ComparatorWithLambda {

    /**
     * 功能:
     *      以匿名类的方式定义比较器
     */
    @Test
    public void test1() {
        Comparator<Banana> comparator = new Comparator<Banana>() {
            @Override
            public int compare(Banana o1, Banana o2) {
                int i = o1.getSize().compareTo(o2.getSize());
                if(i == 0) {
                    i = o1.getName().compareTo(o2.getName());
                }
                return i;
            }
        };
    }

    @Test
    public void test2() {
        Comparator<Banana> comparator = (banana, anotherBanana) -> {
            int comparResult = Integer.compare(banana.getSize(), anotherBanana.getSize());
            if(comparResult == 0) {
                comparResult = banana.getName().compareTo(anotherBanana.getName());
            }
            return comparResult;
        };
    }

    /**
     * 功能:
     *      比lambda更简洁的实现.
     */
    @Test
    public void test3() {
        Comparator<Banana> comparator = Comparator.comparingInt(Banana::getSize).thenComparing(Banana::getName);
    }

    @Test
    public void test4() {
        Banana banana = new Banana();
        // & 是 Java8 的新语法，表示同时满足两个约束（约束这个词不知道用的恰不恰当）, 也就是这个类同时实现了这两个接口。
        Comparator<Banana> banana1 = (Comparator<Banana> & Serializable) banana;
    }

}
